package com.example.administrator.pms.Home;

import android.app.AlertDialog;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.example.administrator.pms.R;
import com.example.administrator.pms.bean.Image;
import com.example.administrator.pms.bean.Picture;
import com.example.administrator.pms.dao.PictureCollectDao;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.DownloadFileListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;

/**
 * Created by Administrator on 2018/4/21.
 */

public class HomeFragment extends Fragment {
    @Bind(R.id.gridview)
    GridView gridview;

    //查看图片按钮

    //显示图片名称的list


    ArrayList names = null;
    ArrayList descs = null;
    ArrayList fileNames = null;
    @Bind(R.id.iv_search)
    ImageView ivSearch;
//    @Bind(R.id.look)
//    Button look;

//    @Bind(R.id.show_list)
//    ListView show_list;
    @Bind(R.id.et_search)
    EditText etSearch;
    @Bind(R.id.download)
    Button download;



    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    //    public class companyInfo{
//        private Context context;
//        public companyInfo(Context context){
//            this.context = context;
//        }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_home, null);
        ButterKnife.bind(this, view);


        names = new ArrayList();
        descs = new ArrayList();
        fileNames = new ArrayList();

//        添加指定目录
        String path = "/storage/emulated/0/DCIM/Image";
        //selection: 指定查询条件
        String selection = MediaStore.Images.Media.DATA + " like '%" + path + "%'";
        //设定查询目录
        Cursor cursor = getActivity().getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, selection, null, null);

        while (cursor.moveToNext()) {
            //获取图片的绝对地址
            byte[] data = cursor.getBlob(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            fileNames.add(new String(data, 0, data.length - 1));
        }

//        gridView = (GridView) findViewById(R.id.gridview);
        PictureAdapter adapter = new PictureAdapter(fileNames, getActivity());
        gridview.setAdapter(adapter);

        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                Toast.makeText(getActivity(), "pic" + (position + 1), Toast.LENGTH_SHORT).show();
            }
        });


//        look.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//
//                //添加指定目录
//                String path = "/storage/emulated/0/DCIM/Image";
//                //selection: 指定查询条件
//                String selection = MediaStore.Images.Media.DATA + " like '%" + path + "%'";
//                //设定查询目录
//
//                //定义selectionArgs：
//                String[] selectionArgs = {path + "%"};
//
//                Cursor cursor = getActivity().getContentResolver().query(
//                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, selection, null, null);
//                while (cursor.moveToNext()) {
//                    //获取图片的名称
//                    String name = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME));
//                    //获取图片的绝对地址
//                    byte[] data = cursor.getBlob(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
//                    //获取图片的详细信息
//                    String desc = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DESCRIPTION));
//                    names.add(name);
//                    descs.add(desc);
//                    fileNames.add(new String(data, 0, data.length - 1));
//
////                    View image = getActivity().getLayoutInflater().inflate(R.layout.base_line, null);
////
////                    ImageView list_image = (ImageView) image.findViewById(R.id.list_image);
////                    list_image.setImageBitmap(BitmapFactory.decodeFile(new String(data, 0, data.length - 1)));
//                }
//
//                List<Map<String, Object>> listItems = new ArrayList<>();
//                for (int i = 0; i < names.size(); i++) {
//                    Map<String, Object> map = new HashMap<>();
//                    map.put("name", names.get(i));
//                    map.put("desc", descs.get(i));
//                    map.put("image", fileNames.get(i));
//                    listItems.add(map);
//                }
//                //设置adapter
//                SimpleAdapter adapter = new SimpleAdapter(getActivity(), listItems,
//                        R.layout.base_line, new String[]{"name", "image"}, new int[]{R.id.name, R.id.list_image});
//
//                show_list.setAdapter(adapter);
//
//
//            }
//        });

        ///list的点击事件
//        show_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                View viewDiag = getActivity().getLayoutInflater().inflate(R.layout.base_view, null);
//
//                ImageView image = (ImageView) viewDiag.findViewById(R.id.image);
//                image.setImageBitmap(BitmapFactory.decodeFile((String) fileNames.get(i)));
//
//                new AlertDialog.Builder(getActivity()).setView(viewDiag)
//                        .setPositiveButton("确定", null).show();
//
//                String url = fileNames.get(i).toString();
//                String name = names.get(i).toString();
//                String label = "熊猫";
//                Picture picture = new Picture(url, null, name, label);
//                PictureCollectDao pictureCollectDao = new PictureCollectDao(getActivity());
//                pictureCollectDao.insertPicture(picture);
//
//                View viewDiag = getActivity().getLayoutInflater().inflate(R.layout.base_message, null);
//                new AlertDialog.Builder(getActivity()).setView(viewDiag).show();
//            }
//        });

        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    @OnClick(R.id.iv_search)
    public void onViewClicked() {
        List<Map<String, Object>> listItems = new ArrayList<>();


        listItems.clear();

        SimpleAdapter adapter1 = new SimpleAdapter(getActivity(), listItems,
                R.layout.base_line, null, null);

//        show_list.setAdapter(adapter1);

        //添加指定搜索条件
        String searchinfo;
        searchinfo = etSearch.getText().toString();
        //添加指定目录
//                String path = "/storage/emulated/0/DCIM/Camera";
        //selection: 指定查询条件
        String selection = MediaStore.Images.Media.DATA + " like '%" + searchinfo + "%'";
        //设定查询目录

//                //定义selectionArgs：
//                String[] selectionArgs = {path + "%"};

        Cursor cursor = getActivity().getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, selection, null, null);
        while (cursor.moveToNext()) {
            //获取图片的名称
            String name = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME));
            //获取图片的生成日期
            byte[] data = cursor.getBlob(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            //获取图片的详细信息
            String desc = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DESCRIPTION));
            names.add(name);
            descs.add(desc);
            fileNames.add(new String(data, 0, data.length - 1));
        }

        for (int i = 0; i < names.size(); i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("name", names.get(i));
            map.put("desc", descs.get(i));
            map.put("image", fileNames.get(i));
            listItems.add(map);
        }
        //设置adapter
        SimpleAdapter adapter = new SimpleAdapter(getActivity(), listItems,
                R.layout.base_line, new String[]{"name", "image"}, new int[]{R.id.name, R.id.list_image});

//        show_list.setAdapter(adapter);

    }


    @OnClick({R.id.iv_search, R.id.download})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_search:
                break;
            case R.id.download:
                BmobQuery<Image> query = new BmobQuery<>();
                query.findObjects(new FindListener<Image>() {
                    @Override
                    public void done(List<Image> list, BmobException e) {
                        if (e == null) {
                            for(int i=0;i<list.size();i++) {
                                downloadpic(list.get(i).getPic());
                            }
                        }
                    }
                });
//                query.getObject("TY00oZZj", new QueryListener<Image>()
//                {
//                    @Override
//                    public void done(Image image, BmobException e) {
//                        if (e == null) {
//                            downloadpic(image.getPic());
//                        }
//                    }
//                });
//                BmobQuery.findObjects(new FindListener<Image>() {
//                    @Override
//                    public void done(List<Image> object,BmobException e) {
//                        if(e==null){
//                            for (Image image : object) {
//                                BmobFile bmobfile = image.getPic();
//                                if(file!= null){
//                                    //调用bmobfile.download方法
//                                }
//                            }
//                        }else{
//
//                        }
//                    }
//                });


                break;
        }
    }

    private void downloadpic(BmobFile pic) {
        File path = new File("/storage/emulated/0/DCIM/Image", pic.getFilename());
        pic.download(path, new DownloadFileListener() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    Toast.makeText(getActivity(), "成功" + s, Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onProgress(Integer integer, long l) {

            }
        });
    }


}


